<template>
	<div class="login">
		<van-nav-bar :title='isLogin?"登录":"注册"' left-text="" left-arrow  @click-left='backfn'>
			<template #right>
				<van-icon name="ellipsis" size="18" />
			</template>
		</van-nav-bar>

			<van-form @submit="onSubmit" class="frombox">
				<van-field v-model="username" name="用户名" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
				<van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
				<template>
					<Verify 
					@success="alert('success')" 
					@error="alert('error')" 
					:type="2" 
					:showButton="false"
					ref="verify"
					></Verify>
				</template>
				<p @click="changeLogin">{{isLogin?'立即注册':"已有账号,立即登录"}}</p>
				<div style="margin: 16px;">
					<van-button round block type="info" native-type="submit">{{isLogin?'登录':"注册"}}</van-button>
				</div>
			</van-form>
	
	</div>
</template>

<script>
	import {register,login} from "../api/index.js";
	import Verify from 'vue2-verify'

	export default {
		name: 'Login',
		data() {
			return {
				username: '',
				password: '',
				checkValue:false,
				isLogin:true
			};
		},
		methods: {
			backfn(){
				this.$router.back();
			},
			alert(text) {
				//console.log(text)
				this.checkValue=text=="success"?true:false
			},
			changeLogin(){
				this.isLogin=!this.isLogin;
				this.username=this.password="";
				this.$refs.verify.refresh();
			},
			onSubmit(values) {
				// console.log(this.$refs.verify);
				// console.log(this.$refs.verify.checkCode());
				this.$refs.verify.checkCode();
				if(this.checkValue){//登录注册功能
					if(this.isLogin){//登录
						login(this.username,this.password).then(data=>{
							if(data.resultCode==200){
								localStorage.setItem("xftoken",data.data);
								if (this.$route.query.needback == 1) {
								  this.$router.back();
								} else {
								  this.$router.replace("/home");
								}
							}
						})
					}else{//注册
						register(this.username,this.password).then(data=>{
							if(data.resultCode==200){
								this.changeLogin();
							}
						})
					}
					
				}else{//验证码重新刷新
					this.$refs.verify.refresh();
				}
				console.log('submit', values);
			}
		},
		components: {
			Verify
		}
	}
</script>

<style lang='less' scoped>
	.frombox {
		width:80%;
		margin:0 auto;
		margin-top: 100px;
		text-align: center;
		/deep/.cerify-code-panel {
		  display: flex;
		  justify-content: space-between;
		}
	}
</style>
